from django.shortcuts import render
# from rest_framework.generics import API
# Create your views here.

# GET usernames/(?P<username>\w{5,20})/count/
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, ListAPIView,DestroyAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import GenericViewSet

from users import constants
from users import serializers
from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer


class UsernameCountView(APIView):
    """用户名数量"""
    def get(self, request, username):
        user = User.objects.filter(username=username)
        count = user.count()
        data = {
            "username":username,
            "count":count
        }
        return Response(data)


class MobileCountView(APIView):
    """用户名数量"""
    def get(self, request, mobile):
        user = User.objects.filter(mobile=mobile)
        count = user.count()
        data = {
            "mobile":mobile,
            "count":count
        }
        return Response(data)


class UserView(CreateAPIView):
    """
    用户注册
    传入参数：
        username, password, password2, sms_code, mobile, allow
    """
    serializer_class = CreateUserSerializer




# GET /user/
class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer
    # queryset = User.objects.all()
    permission_classes = [IsAuthenticated,]
    def get_object(self):
        return self.request.user


# PUT /email/

class EmailView(UpdateAPIView):
    """保存用户邮箱"""
    permission_classes = [IsAuthenticated, ]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user



# GET /emails/verification/?token=xxx
class VerifyEmailView(APIView):
    permission_classes = [AllowAny]
    def get(self, request):
        # 获取token
        token = request.query_params.get("token")
        if not token:
            return Response({"message":"缺少toekn"}, status=status.HTTP_400_BAD_REQUEST)
        # 验证token
        # user = User.verify_token_user(token)
        user = request.user.verify_token_user(token)
        if user is  None:
            return Response({"message":"当前用户不存在", },status=status.HTTP_400_BAD_REQUEST)
        user.email_active_status = True
        user.save()

        return Response({"message":"success"})



# GET /addresses/
class AddressView(ListAPIView,CreateAPIView, DestroyAPIView,UpdateAPIView, GenericViewSet):
    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]



    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        queryset =self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = request.user

        return Response({
            'user_id':user.id,
            'default_address_id':user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses':serializer.data,
        })
        # return Response({
        #     'user_id': user.id,
        #     'default_address_id': user.default_address_id,
        #     'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
        #     'addresses': serializer.data,
        # })


    def create(self, request, *args, **kwargs):
        count =  self.request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({"message":"保存地址数量超过上限"},status=status.HTTP_400_BAD_REQUEST)
        return super().create(request, *args, **kwargs)


    def destroy(self,request, *args, **kwargs):
        """删除地址"""
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response({"message":"已删除"},status=status.HTTP_204_NO_CONTENT)





    # put /addresses/pk/status/
    @action(methods=['put'], detail = True)
    def status(self, request, pk):
        """
        设置默认地址
        :param request:
        :param pk:
        :return:
        """
        address = self.get_object()
        user = request.user
        user.default_address = address
        user.save()
        return Response({"message":"ok"},status=status.HTTP_200_OK)

    # put / addresses / pk / title /
    @action(methods=['put'], detail=True)
    def title(self,request,pk):
        address = self.get_object()
        title = request.POST.get('title')
        print(title)
        address.title = title
        address.save()
        return Response({"title":title})
        # address = self.get_object()
        # serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # return Response(serializer.data)
# GET /password/$

# class PassWordApiView(APIView):
#     permission_classes = [IsAuthenticated]
#     # serializer_class = serializers.UserPwdUpdate
#
#     def put(self, request):
#         user = request.user
#         new_pwd = request.data.get("new_pwd")
#         old_pwd = request.data.get("old_pwd")
#         repeat_pwd = request.data.get("repeat_pwd")
#         if not (new_pwd and old_pwd and repeat_pwd) and repeat_pwd != new_pwd:
#             return Response({"message":"缺少数据"}, status=status.HTTP_400_BAD_REQUEST)
#
#
#         if not user.check_password(old_pwd):
#             return Response({"meassage":"密码校验失败"}, status=status.HTTP_400_BAD_REQUEST)
#
#         user.set_password(new_pwd)
#         user.save()
#         return Response({"message":"密码修改成功", "id":user.id})


class PassWordApiView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.UserPwdUpdate

    def get_object(self):
        return self.request.user